
package com.bdtop.dbl.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.SeekBar;

import com.bdtop.dbl.R;
import com.bdtop.dbl.model.Track;
import com.bdtop.dbl.utils.DBLDebug;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: TimeLineSeekBar
 * @Description: TODO
 * @author: wangpeng
 * @date:2014-10-14
 */
public class TimeLineSeekBar extends SeekBar {

    private int seekBarWidth;
    private int seekBarHeight;

    private final int SEEK_BAR_MAX = 86400000; // 24 * 60 * 60 * 1000

    private long startTime;

    public static final int NONE_SELECTED_POINT = -1;
    private int currentIndex = NONE_SELECTED_POINT;
    private List<Long> timePoints = new ArrayList<Long>();

    private OnTimeChangedListener listener;

    public interface OnTimeChangedListener {
        void onTimeChanged(int currentIndex);
    }

    public void setOnTimeChangedListener(OnTimeChangedListener listener) {
        this.listener = listener;
    }

    public TimeLineSeekBar(Context context) {
        super(context);
        init(context);
    }

    public TimeLineSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TimeLineSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    @SuppressLint("SimpleDateFormat")
    public void initTimePoint(List<Track> trackList, long timeMillisOfselectedDay) {
        timePoints.clear();
        // part 1: init start time - convert selected day to long time millis.
        startTime = timeMillisOfselectedDay;
        // part 2: init time point - convert Track object to TimePoint object.
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < trackList.size(); i++) {
            Track t = trackList.get(i);
            try {
                Date d = sdf.parse(t.getTime());
                timePoints.add(d.getTime());
            } catch (ParseException e) {
                // the track time properties format not use [yyyy-MM-dd HH:mm:ss]
            }
        }
        
        DBLDebug.logw("timePointSize:" + trackList.size());
    }

    public void updateProgressByCurrentIndex(int index) {
        currentIndex = index;
//        if(currentIndex >= timePoints.size()){
//        	currentIndex = timePoints.size() - 1;
//        }
        if (timePoints.size() > 0) {
            int currentProgress = (int) (timePoints.get(currentIndex) - startTime);
            DBLDebug.logd("currentProgress by clickset?:" + currentProgress);
            this.setProgress(currentProgress);
        }
    }

    private void init(Context context) {
        this.thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.point);
        this.setMax(SEEK_BAR_MAX);
        this.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                currentProgress = arg1;
                DBLDebug.logd("onProgressChanged:" + currentProgress);
                currentIndex = NONE_SELECTED_POINT;
                for (int i = timePoints.size() - 1; i >= 0; i--) {
                    if (currentProgress > timePoints.get(i) - startTime) {
                    	 DBLDebug.logd("currentProgress" + currentProgress + "timePoints.get(i):" + timePoints.get(i) + "starttime"  +startTime);
                        currentIndex = i;
                        break;
                    }
                }
                DBLDebug.logd("the currentIndex is "  + currentIndex +  " and timePoints size is " + timePoints.size());
                
                //fix? 
                currentIndex = currentIndex + 1;
                
                if (listener != null) {
                    listener.onTimeChanged(currentIndex);
                }
            }
        });
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        seekBarWidth = right - left;
        seekBarHeight = bottom - top;
    }

    Paint paint = new Paint();

    private int currentProgress = 0;
    private Bitmap thumb;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (timePoints.size() < 1) {
            // the track time point has not init on the timebar
        } else {
            for (int i = 0; i < timePoints.size(); i++) {
                int cx = calculateTimeSpacing(timePoints.get(i));
                if (cx != -1) {
                    if (i == currentIndex - 1)
                        paint.setColor(Color.parseColor("#F83A3A"));
                    else
                        paint.setColor(Color.parseColor("#FFFFFF"));
                    canvas.drawCircle(cx, seekBarHeight / 2, seekBarHeight / 5, paint);
                }
            }
        }

        int marginRight = (int) ((currentProgress * 1.0f / SEEK_BAR_MAX) * (seekBarWidth - seekBarHeight));
        RectF f = new RectF(marginRight, 0, marginRight + seekBarHeight, seekBarHeight);
        canvas.drawBitmap(thumb, null, f, paint);
    }

    private int calculateTimeSpacing(Long point) {
        long ratioOftheBar = point - startTime;

        if (ratioOftheBar < 0 || ratioOftheBar > SEEK_BAR_MAX) {
            DBLDebug.logw("the track point time are not in the seleted day");
            return -1;
        }
        return (int) ((double) ratioOftheBar / SEEK_BAR_MAX
                * (seekBarWidth - seekBarHeight) + (seekBarHeight) / 2);
    }
}
